package com.credit.service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.PostConstruct;
import javax.transaction.Transactional;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springside.modules.persistence.DynamicSpecifications;
import org.springside.modules.persistence.SearchFilter;

import com.credit.entity.CreditBaseParam;
import com.credit.repository.CreditBaseParamDao;

@Service("creditBaseParamService")
@Transactional
public class CreditBaseParamService {
	private static final Log log = LogFactory.getLog(CreditBaseParamService.class);
	
	@Autowired
	private CreditBaseParamDao creditBaseParamDao;
	
    public static Map<String,Object> paramsMap = new HashMap<String,Object>();
	
	@PostConstruct
	public void init() {
        log.info("初始化基础数据......");
		
		List<CreditBaseParam> list = getList();
		
		for(CreditBaseParam baseParam:list){
			if(baseParam.getParentId()==0){//父节点
				Map<String,Object> parentMap = (Map<String, Object>) paramsMap.get(baseParam.getLabel());
				if(parentMap == null){
					parentMap = new HashMap<String,Object>();
					parentMap.put("list", new ArrayList<>());
				}
				
				
				parentMap.put("name", baseParam.getName());
				parentMap.put("label", baseParam.getLabel());
				
				paramsMap.put( baseParam.getLabel(), parentMap);
			}else{
				Map<String,Object> parentMap = (Map<String, Object>) paramsMap.get(baseParam.getName());
				if(parentMap == null){
					parentMap = new HashMap<String,Object>();
					parentMap.put("list", new ArrayList<>());
				}
				
				List paramList = (List) parentMap.get("list");
				Map<String,Object> subMap = new HashMap<String,Object>();
				subMap.put("id", baseParam.getId());
				subMap.put("type", baseParam.getType());
				subMap.put("name", baseParam.getName());
				subMap.put("label", baseParam.getLabel());
				subMap.put("value", baseParam.getValue());
				subMap.put("selected", baseParam.getSelected());
				paramList.add(subMap);
				
				parentMap.put("list", paramList);
				
				paramsMap.put(baseParam.getName(), parentMap);
				
			}
		}
		
	}

	public List<CreditBaseParam> getList() {
		
		Map<String, SearchFilter> filters = new HashMap<String, SearchFilter>();
	
		Specification<CreditBaseParam> spec = DynamicSpecifications.bySearchFilter(filters.values(), CreditBaseParam.class);
		
		return creditBaseParamDao.findAll(spec);
	}

	public Map<String, Object> getParamsMap() {
		
		return paramsMap;
	}

}
